<?php
/**
 * 牌局日志备份和缓存实日志
 * Created by PhpStorm.
 * Keter
 * 2016/8/1
 * @守护进程
 */
class RsyncPaijuBackLogHandler extends ScriptBase
{
    /**
     * 游戏服保存的牌局日志KEY
     */
    const LOG_NAME = 'cardLog';

    /**
     * 出错备份
     */
    const QUEEN_BACKUP_NAME = 'cardLogBackup';

    /**
     * 当前脚本暂停标志
     * 同类结果为TRUE时则暂停和停止，如1
     */
    const SUSPEND_TAG = 'PAIJU_LOG_HANDLER_SUSPEND'; //暂停

    /**
     * 停止脚本标志
     */
    const STOP_TAG = 'PAIJU_LOG_HANDLER_STOP'; //停止

    /**
     * PHP用牌局日志缓存KEY
     */
    const CACHE_KEY = 'PJL';

    /**
     * 读取数据处理条数  add by tmac
     */
    const CACHE_LIMIT_NUMBER = 1000;

    /**
     * 日志文件大小  add by tmac
     */
    const LOG_FILE_SIZE = 2540000;
    /**
     * 过期时间
     */
    private $_expireTime;

    /**
     * 牌局日志Redis
     */
    protected $paijuRedis;

    public function test() {
        $this->e('日志备份写入文件失败', $data);
        echo 1;
        return false;
    }

    /**
     * 逻辑代码
     */
    public function logic()
    {     
        set_time_limit(0);

        $this->paijuRedis = $this->redis('paiju_log');
        //获取列表长度，来取条数
        $lenth = $this->paijuRedis->lLen(self::QUEEN_BACKUP_NAME);
        if(empty($lenth)){
            echo 'no data need to save!';
            exit;
        }

        $offset = 20;
        for ($i=0; $i < $offset; $i++ ){
            $lastElement =  $this->paijuRedis->rpop(self::QUEEN_BACKUP_NAME);
			$this->paijuRedis->lpush('cardLogBackup', $lastElement);

            //is_array($lastElement) && $lastElement = reset($lastElement);
            $data = json_decode($lastElement, true);
			if(!$data) {
				continue;
			}
			
            $result = $data ?  $this->backup2db($data) : true;
            // 如果没有处理成功，则放入备份队列
            //if ( !$result ) {
                //$this->paijuRedis->lpush('cardLogBackup', $lastElement);   
            //}
        }

        $this->deinitRedis('paiju_log');

        $last = $lenth - $offset;
        echo '==== '.$last ." reacord  need to save ====".PHP_EOL;
        exit;
        // add by lyon
    }


    /**
     * 写入牌局数据库
     * @param $data
     */
    public function backup2db($data)
    {
        $paijuLog = new PaijuLog();
        $paijuLog->isRedisLog(false);

        //$paijuLog->zuTable = 'paizu_log_back_0329';
        //$paijuLog->juTable = 'paiju_log_back_0329';

        /**
         * 保存牌局
         */
        $juData = $paijuLog->saveBackPaijuLog($data);
        /**
         * 保存牌组
         */
        //---add by tmac 2016-12-20 修复 返回错误bug

        $result = count( $juData ) < 1 ? [] : $paijuLog->saveBackPaizuLog($data, $juData);
        count( $result ) < 1  && $result =  false;
        //---end add
        //$result = $paijuLog->savePaizuInfo($data, $juData);  //注释 by tmac 2016-12-20
        if (!$result) {
            error_log(json_encode($data).PHP_EOL,3,'./data/logs/back_0329.log');
        }

        return $result;
    }
}
?>

